package com.peng.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.domain.ResponseResult;
import com.peng.domain.entity.Category;
import com.peng.domain.entity.User;
import com.peng.domain.vo.CategoryVo;
import com.peng.domain.vo.ExcelCategoryVo;
import com.peng.domain.vo.PageVo;
import com.peng.enums.AppHttpCodeEnum;
import com.peng.exception.SystemException;
import com.peng.service.CategoryService;
import com.peng.utils.BeanCopyUtils;
import com.peng.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory() {
        List<CategoryVo> list = categoryService.listAllCategory();
        return ResponseResult.okResult(list);
    }

    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        // 设置下载文件的请求头
        try {
            WebUtils.setDownLoadHeader("分类.xlsx", response);
            // 获取需要导出的数据
            List<Category> categoryVos = categoryService.list();
            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            // 把数据写入到excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (Exception e) {
//            e.printStackTrace();
            // 如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    @GetMapping("/list")
    public ResponseResult getList(Integer pageNum, Integer pageSize, Category category) {
        PageVo pageVo = categoryService.getPageList(pageNum, pageSize, category);
        return ResponseResult.okResult(pageVo);
    }

    @PostMapping
    public ResponseResult add(@RequestBody Category category){
        if (!StringUtils.hasText(category.getName())){
            throw new SystemException(AppHttpCodeEnum.CATEGORYNAME_ISNOTNULL);
        }
        if (NameExist(category.getName())){
            throw new SystemException(AppHttpCodeEnum.CATEGORYNAME_EXIST);
        }
        categoryService.save(category);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult getCateGoryById(@PathVariable("id") Long id){
        Category category = categoryService.getById(id);
        return ResponseResult.okResult(category);
    }

    @PutMapping
    public ResponseResult edit(@RequestBody Category category){
        if (!StringUtils.hasText(category.getName())){
            throw new SystemException(AppHttpCodeEnum.CATEGORYNAME_ISNOTNULL);
        }
        if (NameExist(category.getName())){
            throw new SystemException(AppHttpCodeEnum.CATEGORYNAME_EXIST);
        }
        categoryService.updateById(category);
        return ResponseResult.okResult();
    }
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable("id") Long id){
        categoryService.removeById(id);
        return ResponseResult.okResult();
    }

    private boolean NameExist(String name) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Category::getName, name);
        int count = categoryService.count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
}
